package ws

import (
	"flag"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"
	"trpg-common/config"
	"trpg-common/logger"
)

var addr = flag.String("addr", ":"+config.GetString("ws-port"), "http service address")

func InitWs() {
	hub := newHub()
	go hub.run()
	logger.Logger.Info("start ws server")
	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		s := r.URL.String()
		split := strings.Split(s, "&")
		roomId, err := strconv.ParseInt(strings.Split(split[0], "roomId=")[1], 10, 64)
		if err != nil {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
		uid := strings.Split(split[1], "uid=")[1]
		serveWs(roomId, uid, hub, w, r)
	})
	server := &http.Server{
		Addr:              *addr,
		ReadHeaderTimeout: 3 * time.Second,
	}
	err := server.ListenAndServe()
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
